/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Controllers;

import ModeloDominio.Utente;
import javax.annotation.Resource;
import javax.enterprise.context.spi.Context;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;

/**
 *
 * @author LCF
 */
public class UtenteController {
    /**
     * <p>The <code>PersistenceContext</code>.</p>
     */
      @PersistenceContext
    private EntityManagerFactory emf;
   @Resource
    private UserTransaction utx;
  

    public UtenteController() {
        emf = Persistence.createEntityManagerFactory("SISOPersistence");
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Utente utente) throws Exception {
        EntityManager emf = null;
        try {
            emf = getEntityManager();
            utx.begin();
            emf.persist(utente);
            utx.commit();
        } catch (Exception ex) {
            if (findUtente(utente.getId()) != null) {
                //throw new PreexistingEntityException("Utente " + utente + " already exists.", ex);
                System.out.println("Utente " + utente + " already exists.");
            }
            throw ex;
        } finally {
            if (emf != null) {
                emf.close();
            }
        }
    }

    private Utente findUtente(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Utente.class, id);
        } finally {
            em.close();
        }
    }

}
